<template>
  <PageWrapper v-loading="loadingRef" content-full-height fixed-height dense>
    <AdVxeTable @register="registerPrintTable">
      <template #tools>
        <Authority value="Root.Report.Admin.Print.CreatePrints">
          <a-button type="primary" @click="handleCreatePrintDetail">
            <Icon icon="ant-design:plus-circle-outlined" />{{ t('report.route.print.printSetup.addPrint') }}
          </a-button>
        </Authority>
      </template>

      <template #actionCol="{ row }">
        <TableAction
          outside
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: t('common.delText'),
              auth: 'Root.Report.Admin.Print.DeletePrints', // 权限控制
              // ifShow: (_action) => {
              //   return row?.Deletable === true; // 根据业务控制是否显示: 是否可删除的数据权限状态
              // },
              popConfirm: {
                title: t('common.delConfirmText'),
                placement: 'left',
                confirm: handleDeletePrintDetail.bind(null, row),
              },
            },
          ]"
          :drop-down-actions="[
            {
              icon: 'clarity:details-line',
              label: t('common.detailText'),
              onClick: handleReadPrintDetail.bind(null, row),
            },
            {
              icon: 'clarity:note-edit-line',
              label: t('common.editText'),
              auth: 'Root.Report.Admin.Print.UpdatePrints', // 权限控制
              onClick: handleEditPrintDetail.bind(null, row),
            },
          ]"
        />
      </template>

      <template #expandedRowRender="{ row }">
        <AdVxeTable
          @register="registerTemplateTable"
          :search-info="{
            Rules: [{ Field: 'PrintId', Value: row.Id, Operate: FilterOperateEnum.Equal }],
            Operate: FilterOperateEnum.And,
            Groups: [],
            Level: 1,
          }"
        >
          <template #tools>
            <Authority value="Root.Report.Admin.Print.CreateTemplates">
              <a-button type="primary" @click="handleCreateTemplateDetail(row)">
                <Icon icon="ant-design:plus-circle-outlined" />{{ t('report.route.print.printSetup.addPrintTemplate') }}
              </a-button>
            </Authority>
          </template>

          <template #actionCol="data">
            <TableAction
              outside
              :actions="[
                {
                  icon: 'ant-design:delete-outlined',
                  color: 'error',
                  tooltip: t('common.delText'),
                  auth: 'Root.Report.Admin.Print.DeleteTemplates', // 权限控制
                  popConfirm: {
                    title: t('common.delConfirmText'),
                    placement: 'left',
                    confirm: handleDeleteTemplateDetail.bind(null, data.row),
                  },
                },
              ]"
              :drop-down-actions="[
                {
                  icon: 'clarity:details-line',
                  label: t('common.detailText'),
                  onClick: handleReadTemplateDetail.bind(null, row, data.row),
                },
                {
                  icon: 'clarity:note-edit-line',
                  label: t('common.editText'),
                  auth: 'Root.Report.Admin.Print.UpdateTemplates', // 权限控制
                  onClick: handleEditTemplateDetail.bind(null, row, data.row),
                },
              ]"
            />
          </template>
        </AdVxeTable>
      </template>
    </AdVxeTable>

    <PrintTemplateDetailModal
      @register="registerTemplateDetailFormModal"
      :after-submit-func="handleAfterTemplateDetailSubmit"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import type { AjaxResult } from '#/request';

  import { h, ref } from 'vue';

  import { isString } from '@eacloud/utils';

  import {
    createPrints,
    deletePrints,
    deleteTemplates,
    readPrints,
    readTemplates,
    updatePrints,
  } from '@/api/report/admin/print';
  import { useModal } from '@/components/AdVxeModal';
  import { AdVxeTable, TableAction, useAdVxeTable } from '@/components/AdVxeTable';
  import { Authority } from '@/components/Authority';
  import Icon from '@/components/Icon/Icon.vue';
  import { PageWrapper } from '@/components/Page';
  import { FilterOperateEnum } from '@/enums/filterOperateEnum';
  import { FormModeEnum } from '@/enums/formEnum';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';

  import { printColumns, templateColumns } from './printsetup.data';
  import PrintTemplateDetailModal from './PrintTemplateDetailModal.vue';

  defineOptions({ name: 'PrintSetupPage' });

  const { t } = useI18n();
  const { createMessage, createErrorModal } = useMessage();

  const loadingRef = ref(false);
  function openWrapLoading() {
    loadingRef.value = true;
  }
  function closeWrapLoading() {
    loadingRef.value = false;
  }

  const [registerPrintTable, { openDetailForm: openPrintDetailForm, reload: reloadPrintTable }] = useAdVxeTable({
    id: 'report-print-setup-page-table',
    // 表标题呈现器
    title: t('report.route.print.printSetup.printList'),
    // 表格数据接口请求对象
    api: readPrints,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'report_printsetup_print_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('report.route.print.printSetup.printTitle'),
      // 实体新增接口请求对象
      createApi: createPrints,
      // 实体更新接口请求对象
      updateApi: updatePrints,
    },
    // 表单列信息 AdColumn[]
    columns: printColumns,
    // 展开行
    expand: true,
    // 展开行配置项（不支持虚拟滚动）
    expandConfig: {
      // 触发方式（注：当多种功能重叠时，会同时触发）
      // default（点击按钮触发）, cell（点击单元格触发）, row（点击行触发）
      trigger: 'row',
      // height: 500,
    },
    // 使用搜索表单
    searchForm: true,
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    // 表格右侧操作列配置 AdColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });
  /** 查看详情 */
  async function handleReadPrintDetail(record: any) {
    openPrintDetailForm(FormModeEnum.ReadOnly, record);
  }
  /** 处理创建 */
  async function handleCreatePrintDetail() {
    openPrintDetailForm(FormModeEnum.Add);
  }
  /** 处理编辑 */
  async function handleEditPrintDetail(record: any) {
    openPrintDetailForm(FormModeEnum.Edit, record);
  }
  /** 处理删除 */
  async function handleDeletePrintDetail(record: any) {
    // console.log(record);
    if (record && record.Id) {
      try {
        openWrapLoading();
        const result = await deletePrints([record.Id]);
        if (result.Succeeded) {
          createMessage.success(t('common.successText'));
          reloadPrintTable();
        }
      } finally {
        closeWrapLoading();
      }
    }
  }

  const [registerTemplateTable, { reload: reloadTemplateTable }] = useAdVxeTable({
    id: 'report-print-setup-page-template-table',
    // 表标题呈现器
    title: t('report.route.print.printSetup.printTemplateList'),
    // 表格数据接口请求对象
    api: readTemplates,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'print_template_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('report.route.print.printSetup.printTemplateTitle'),
    },
    // 表单列信息 AdColumn[]
    columns: templateColumns,
    // 使用搜索表单
    searchForm: false,
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    height: 500,
    // 表格右侧操作列配置 AdColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  const [registerTemplateDetailFormModal, templateDetailFormModalMethods] = useModal();
  /** 查看详情 */
  async function handleReadTemplateDetail(printRecord: any, templateRecord: any) {
    // console.log({ printRecord, templateRecord });
    templateDetailFormModalMethods.openModal(true, {
      formMode: FormModeEnum.ReadOnly,
      printRecord,
      templateRecord,
    });
  }
  /** 处理创建 */
  async function handleCreateTemplateDetail(printRecord: any) {
    templateDetailFormModalMethods.openModal(true, {
      formMode: FormModeEnum.Add,
      printRecord,
      templateRecord: null,
    });
  }
  /** 处理编辑 */
  async function handleEditTemplateDetail(printRecord: any, templateRecord: any) {
    templateDetailFormModalMethods.openModal(true, {
      formMode: FormModeEnum.Edit,
      printRecord,
      templateRecord,
    });
  }
  /** 处理删除 */
  async function handleDeleteTemplateDetail(templateRecord: any) {
    // console.log(record);
    if (templateRecord && templateRecord.Id) {
      try {
        openWrapLoading();
        const result = await deleteTemplates([templateRecord.Id]);
        if (result.Succeeded) {
          createMessage.success(t('common.successText'));
          reloadTemplateTable();
        }
      } finally {
        closeWrapLoading();
      }
    }
  }
  /** 处理详情表单提交后回调，返回true关闭窗体 */
  async function handleAfterTemplateDetailSubmit(
    formMode: FormModeEnum,
    result?: AjaxResult | null,
    _printRecord?: any,
    _templateRecord?: any,
  ) {
    if (result?.Succeeded) {
      if (result?.Content) {
        createMessage.success(result.Content);
      }
    } else {
      if (result?.Data && isString(result?.Data)) {
        createErrorModal({
          zIndex: 999999999,
          title: () => h('span', t('sys.api.errorTip')),
          content: () => h('span', result?.Data),
        });
      }
    }
    switch (formMode) {
      case FormModeEnum.Add:
      case FormModeEnum.Edit:
      case FormModeEnum.Delete:
        await reloadTemplateTable();
        break;
    }
    return true;
  }
</script>
